package com.mikepenz.app.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.mikepenz.app.R;
import com.mikepenz.pay.PayResult;
import com.mikepenz.pay.SignUtils;
import com.mikepenz.presenter.imp.PayPresenterImp;
import com.mikepenz.utils.CookicUntil;
import com.mikepenz.view.PayView;
import com.quickdv.activity.BaseActivity;
import com.quickdv.until.AlertHelper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.InjectView;

/**
 * 充值支付界面
 */

public class RendingActivity extends BaseActivity implements View.OnClickListener, PayView {
    ProgressDialog dialog;
    RadioButton yinlian_rb, ali_rb, weichar_rb;
    LinearLayout yinlian_ll, ali_ll, weichar_ll;
    Button pay_bt;
    @InjectView(R.id.pay_balance)
    TextView payBalance;
    @InjectView(R.id.order_code)
    TextView orderCode;
    @InjectView(R.id.pay_value)
    EditText payValue;

    PayPresenterImp presenter;
    String orderCodeValue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Handle Toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }


    @Override
    public int getLayoutID() {
        return R.layout.activity_pay;
    }

    @Override
    public void initView() {

//        yinlian_ll = findView(R.id.pay_yinlian);
//        yinlian_rb = findView(R.id.pay_chose_yinlian);
        ali_ll = findView(R.id.pay_ali);
        ali_rb = findView(R.id.pay_chose_ali);
//        weichar_ll = findView(R.id.pay_weichar);
//        weichar_rb = findView(R.id.pay_chose_weichar);
        pay_bt = findView(R.id.pay);

//        yinlian_ll.setOnClickListener(this);
//        yinlian_rb.setOnClickListener(this);
//        weichar_ll.setOnClickListener(this);
//        weichar_rb.setOnClickListener(this);
        ali_ll.setOnClickListener(this);
        ali_rb.setOnClickListener(this);
        pay_bt.setOnClickListener(this);

        payBalance.setText(CookicUntil.getCardBean().getMoney() + "元");
//        orderCode.setText(UUID.randomUUID().toString());
        AlertHelper helper = new AlertHelper(this);
        dialog = helper.LoadingAlert();

    }

    @Override
    public void initActionbar() {
        getSupportActionBar().setTitle(R.string.title_activity_pay);
    }

    @Override
    public void initData() {
        presenter = new PayPresenterImp(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.pay_yinlian:
//            case R.id.pay_chose_yinlian:
//                clearAllChose();
//                yinlian_rb.setChecked(true);
//                break;
            case R.id.pay_ali:
            case R.id.pay_chose_ali:
                clearAllChose();
                ali_rb.setChecked(true);
                break;
//            case R.id.pay_weichar:
//            case R.id.pay_chose_weichar:
//                clearAllChose();
//                weichar_rb.setChecked(true);
//                break;
            case R.id.pay:
                if (pay(v)) {
//                    if (order_id != null)
                    presenter.getOrderCode();


                }

        }
    }

    private void clearAllChose() {
//        yinlian_rb.setChecked(false);
//        weichar_rb.setChecked(false);
        ali_rb.setChecked(false);
    }

    private boolean pay(View view) {
        if (TextUtils.isEmpty(payValue.getText())){
            payValue.setError("充值金额不能为空");
            return false;
        } else if(payValue.getText().toString().startsWith("0")){
            payValue.setError("充值金额不合法");
            return false;
        }
        else {
//        if (yinlian_rb.isChecked()) {
//            return true;
//        } else

            if (ali_rb.isChecked()) {
                return true;
            }
//        else if (weichar_rb.isChecked()) {
//            return true;
//        }


            else {
                Toast.makeText(this, "请选择支付方式", Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }

    @Override
    public void setOrderCode(String orderCode) {
        this.orderCode.setText(orderCode);
    }

    @Override
    public void setMoney(String money) {
        payBalance.setText(money);
    }

    @Override
    public Float getMoney() {
        return Float.valueOf(payValue.getText().toString());
    }

    @Override
    public void payDialogShow(String orderCode) {
        this.orderCode.setText(orderCode);
        this.orderCodeValue =orderCode;
        if(orderCode==null)
            showError("订单获取失败");
        else
            pay();
    }


    @Override
    public void showLoad() {
        if (dialog != null)
            dialog.show();
    }

    @Override
    public void dismissLoad() {
        if (dialog != null) dialog.dismiss();
    }

    @Override
    public void showError(String error) {
        Toast.makeText(this, error, Toast.LENGTH_LONG).show();
    }

    // 商户PID
    public static final String PARTNER = "2088802318326476";
    // 商户收款账号
    public static final String SELLER = "13700882522@139.com";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKEF7DqZnQ+ucZ9o" +
            "RHIfghV5TN90p5sXW86Wx3bUFHCrG0BzUcbYwetMZvMcvK+ZzyOeWiS2oUT+dB1H" +
            "bx+Xb3cUSB1iN6/Umz9UXEHDOFLgN1xMwPuajvUD1/QoUFfhhn6D7u5MDwCqy41m" +
            "JxA5zzcAuKf5DYvg0QjTdZJhnaEVAgMBAAECgYBV6msY+U2sSE+n1mJu4hDulEJI" +
            "GF41ikkZ+amD5bTiSOnJgb5ocs9FVQa5QOQMbezv/FXssOVrgrlBxhOsr4hxEFCg" +
            "pNZb3C6lrpSEnYu6FnblFOBhZ0gUveHWpO+mja+bCsc3O5aV1nJ2p7a7bn3FZr/t" +
            "zF8ZKKMZ7Koj88e2IQJBAM/LJUzsu7Jtj0SHVqOIYuRTGvtC4Yufv1GoovAQKB+o" +
            "bJpwlqV65WQuz4WFVxhFSxOczp9T8BBg3PgO4GgTu8sCQQDGYRVxuFpu003OKTuU" +
            "tAo0z/b32AQZDkeh+NDoFXcNyOvxUzjD0eKamKnF06iTnr5EzeumlrhlskaQ0IXU" +
            "cDqfAkAs9aNodYBXJuVsymuwjn33MRQRcXMjprjajkZS8uv7jZGSCPJPc7vWZVp5" +
            "ZVRm5/dKkw8R4jN7F7o34eAkJMDpAkEAtRR9bJapBayfwuXkWvKUtmx2tPlblDty" +
            "q6jhmFevmseih2A92pFFVXSw08FGialHaKrGxgOiQkIfI6UT5DylZQJAE5PsW/OI" +
            "q8NXWs2QYtKqnBlWIERx7oCOMo6ATW7Ep/lFe4nf9m5+iA6qgfETNk4TzAMDIG0Y" +
            "Zcpla/GjG0t+ew==";
    // 支付宝公钥
    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        CookicUntil.getCardBean().setMoney(CookicUntil.getCardBean().getMoney() + 0.01f);
                        payBalance.setText(CookicUntil.getCardBean().getMoney() + "元");

                        Toast.makeText(RendingActivity.this, "支付成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(RendingActivity.this, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(RendingActivity.this, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(RendingActivity.this, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay() {
        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
                || TextUtils.isEmpty(SELLER)) {
            new AlertDialog.Builder(this)
                    .setTitle("警告")
                    .setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialoginterface, int i) {
                                    //
                                    finish();
                                }
                            }).show();
            return;
        }
        // 订单
        String orderInfo = getOrderInfo("迈佳迈充值订单", "分时租用充值", payValue.getText().toString());

        // 对订单做RSA 签名
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RendingActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     */
    public void check(View v) {
        Runnable checkRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(RendingActivity.this);
                // 调用查询接口，获取查询结果
                boolean isExist = payTask.checkAccountIfExist();

                Message msg = new Message();
                msg.what = SDK_CHECK_FLAG;
                msg.obj = isExist;
                mHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();

    }

    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    }

    /**
     * create the order info. 创建订单信息
     */
    public String getOrderInfo(String subject, String body, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + payValue.getText().toString() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://218.28.168.22:5180/alipay/androidReturn_url.action"
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    public String getOutTradeNo() {
//        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
//                Locale.getDefault());
//        Date date = new Date();
//        String key = format.format(date);
//
//        Random r = new Random();
//        key = key + r.nextInt();
//        key = key.substring(0, 15);
        return orderCodeValue;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

}
